﻿using System.Collections.Generic;
using DataScripter.Database;

namespace DataScripter.Sorters
{
    class TableStructureSorterFirstWithoutIncomingForeignKeys : ISorter<ITableStructure>
    {
        private IDatabaseStructure Database { get; set; }
        private readonly List<ITableStructure> _sortedTables = new List<ITableStructure>(); 

        public TableStructureSorterFirstWithoutIncomingForeignKeys(IDatabaseStructure database)
        {
            Database = database;
        }

        private void AddSorted(ITableStructure table)
        {
            if (_sortedTables.Contains(table))
                return;
            
            foreach (IForeignKey foreignKey in table.ForeignKeysPointingToThisTable)
            {
                AddSorted(Database.GetTable(foreignKey.TableName));
            }
            _sortedTables.Add(table);
        }

        public IEnumerable<ITableStructure> Sort(IEnumerable<ITableStructure> tables )
        {
            foreach (ITableStructure table in tables)
            {
                AddSorted(table);
            }
            return _sortedTables;
        }
    }
}
